<!-- eslint-disable no-undef -->
<template>
  <div class="app-container">
    <div id="map" ref="map" style="width:100%;height:900px;" />
    <div class="colors">
      <dl v-for="(item,index) in colors" :key="index" class="flex">
        <dt :style="{background:item.color}"><b>{{ item.range }}</b></dt>
      </dl>
    </div>
    <div class="tools">
      <el-button @click="showDialog">选择参数进行计算</el-button>
      <el-button type="primary" :disabled="!!layerContent || (gcwdMarkers.length === 0)" :loading="loading" @click="chazhi">插值并保存</el-button>
      <el-button :disabled="!layerContent" @click="showOrHiddenLayer">{{ show?'隐藏图层':'显示图层' }}</el-button>
    </div>
    <main-form ref="mainForm" @addLayer="addToMap" @getGcwdDatas="getGcwdDatas" @resetForm="resetForm" />
  </div>
</template>

<script>

import * as turf from '@turf/turf'
import { mapGetters } from 'vuex'
import { colorsGcwd as colors } from '@/utils/constant'
import mapConfig from '@/config/map'
import MainForm from './components/main-form'
import { save } from '@/api/statistics'
export default {
  components: {
    MainForm
  },
  data() {
    return {
      loading: false,
      created_at: [],
      gcwdMarkers: [],
      map: {},
      urls: mapConfig.mapTypes[mapConfig.initType],
      nrctLayer: null,
      layerContent: null,
      show: false,
      colors,
      markers: [],
      nrct_id: [],
      markerLayers: [],
      options: [{
        value: 1,
        label: '2022-09-01 11:22:00 ~ 2022-09-02 11:22:00'
      }, {
        value: 2,
        label: '2022-07-12 09:00:00 ~ 2022-07-13 12:30:00'
      }]
    }
  },
  computed: {
    ...mapGetters(['project']),
    circlePolygon() {
      const center = [this.project.lng, this.project.lat]
      const radius = 0.1499
      const options = { steps: 100, units: 'kilometers', properties: { foo: 'bar' }}
      return turf.circle(center, radius, options)
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    async save(info) {
      const { msg } = await save('nrct', info)
      this.$message.success(msg)
    },
    resetForm() {
      this.layerContent = null
    },
    chazhi() {
      this.loading = true
      setTimeout(() => {
        const data = this.gcwdMarkers
        var features = data.map(i => {
          return {
            type: 'Feature',
            properties: {
              value: i.gcwd
            },
            geometry: {
              type: 'Point',
              coordinates: [+i.location[0], +i.location[1]]
            }
          }
        }
        )

        var points = turf.featureCollection(features)
        var interpolate_options = {
          gridType: 'points',
          property: 'value',
          units: 'degrees',
          weight: 10
        }

        var grid = turf.interpolate(points, 0.00002, interpolate_options)

        // 适当降低插值结果的精度便于显示
        grid.features.map((i) => (i.properties.value = i.properties.value.toFixed(4)))

        this.grid = grid.features.map((val) => {
          return {
            lat: val.geometry.coordinates[1],
            lng: val.geometry.coordinates[0],
            gcwd: val.properties.value
          }
        })

        var isobands_options = {
          zProperty: 'value',
          commonProperties: {
            'fill-opacity': 1
          },
          breaksProperties: colors.map(val => {
            return { fill: val.color }
          })
        }

        let isobands = turf.isobands(
          grid,
          colors.map(val => val.value),
          isobands_options
        )
        isobands = turf.flatten(isobands)

        const features_filter = []
        isobands.features.forEach((layer) => {
          let intersection = null
          try {
            intersection = turf.intersect(layer, this.circlePolygon)
          } catch (e) {
            layer = turf.buffer(layer, 0)
            intersection = turf.intersect(layer, this.circlePolygon)
          }
          if (intersection != null) {
            intersection.properties = layer.properties
            features_filter.push(intersection)
          }
        })
        isobands.features = features_filter

        const geoArr = isobands
        // eslint-disable-next-line no-undef
        const res = L.geoJson(geoArr, { style: this.getFlexStyle })

        this.addToMap(res)

        this.save({ data: {
          key: this.created_at.join('~'),
          data: this.gcwdMarkers
        }})

        this.loading = false
        console.log(this.loading)
      }, 1000)
    },
    getGcwdDatas(data, created_at) {
      this.gcwdMarkers = data
      this.created_at = created_at
      this.gcwdMarkers.forEach((item) => {
        // eslint-disable-next-line no-undef
        const markerLayer = L.marker([item.location[1], item.location[0]], {
          // eslint-disable-next-line no-undef
          icon: new L.Icon({
            className: 'lmap-icon',
            iconUrl: item.icon,
            iconSize: [8, 8],
            iconAnchor: [8, 8]
          })
        }).addTo(this.map)
        this.markerLayers.push(markerLayer)
        this.$refs.mainForm.hide()
      })
    },
    showDialog() {
      this.$refs.mainForm.show()
    },
    initMap() {
      // eslint-disable-next-line no-undef
      var baseLayer = L.tileLayer(
        this.urls[0], {
          attribution: '...',
          maxZoom: 18
        })

      // eslint-disable-next-line no-undef
      const map = L.map('map', {
        center: [37.467294, 114.913504],
        zoom: 18,
        zoomControl: false,
        maxZoom: 18,
        attributionControl: false,
        layers: [baseLayer]
      })
      this.map = map
    },
    addToMap(res) {
      this.layerContent = res
      this.addLayer()
    },
    addLayer() {
      this.show = true
      this.nrctLayer = this.layerContent.addTo(this.map)

      this.markerLayers.forEach((item) => {
        this.map.removeLayer(item)
      })
    },
    removeLayer() {
      this.show = false
      this.map.removeLayer(this.nrctLayer)
    },
    showOrHiddenLayer() {
      if (this.show) {
        this.removeLayer()
      } else {
        this.addLayer()
      }
    },
    getFlexStyle(feature) {
      return {
        weight: 1,
        opacity: 0,
        color: '#fff',
        fillOpacity: 0.6,
        fillColor: feature.properties.fill }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  position:relative;
  .tools{
    position:absolute;
    top:24px;
    right:24px;
    z-index:999;
  }
}
.colors{
  position:absolute;
  top:24px;
  left:24px;
  z-index:999;
  dl{
    align-items:center;
    font-size:12px;
    dt{
      display:inline-block;
      width:60px;
      height:30px;
      line-height:30px;
      text-align:center;
      margin-right:4px;
      color:#333;
    }
  }
}
</style>
